package com.webapp.controller;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class Upload
 */
public class Upload extends HttpServlet {
	private static final long serialVersionUID = 1L;
    // base directory to store files
	  private static final String BASE_DIRECTORY = "fileText";
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Upload() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if (ServletFileUpload.isMultipartContent(request)){
			  FileItemFactory factory = new DiskFileItemFactory();
		      //  Create a new file upload handler
		      ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
		      // Set upload parameters
		      // See Apache Commons FileUpload for more information
		      // http://jakarta.apache.org/commons/fileupload/using.html
		      servletFileUpload.setSizeMax(-1);
		      try {
		        String directory = "";
		        // Parse the request
		        List items = servletFileUpload.parseRequest(request);
		        // Process the uploaded items
		        Iterator iter = items.iterator();
		        while (iter.hasNext()) {
		          FileItem item = (FileItem) iter.next();
		          // the param tag directory is sent as a request parameter to
		          // the server
		          // check if the upload directory is available
		          if (item.isFormField()) {
		            String name = item.getFieldName();
		            if (name.equalsIgnoreCase("directory")) {
		              directory = item.getString();
		            }
		            // retrieve the files
		          } else {
		            // the fileNames are urlencoded
		            String fileName = URLDecoder.decode(item.getName());
		            File file = new File(directory, fileName);
		            file = new File(BASE_DIRECTORY, file.getPath());
		            System.out.print(fileName);
		            System.out.print(file.getAbsolutePath());
		            // retrieve the parent file for creating the directories
		            File parentFile = file.getParentFile();
		            if (parentFile != null) {
		              parentFile.mkdirs();
		            }
		            // writes the file to the filesystem
		            item.write(file);
		          }
		        }
		      } catch (Exception e) {
		        e.printStackTrace();
		        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		      }
		      response.setStatus(HttpServletResponse.SC_OK);
		    } else {
		      response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
		    }
	}

}
